package com.york.controller;

import com.york.entity.User;
import com.york.service.UserService;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * @author york.young
 * @description Export2Controller:
 * @date 2022/3/31
 */
@Controller
public class JxlsController {
    @Autowired
    private UserService userService;


    /**
     * @description 使用jxls包下的jxls语法来导出excel文件
     * @author york.young
     * http://localhost:8083/exportByJxls
     */
    @GetMapping("exportByJxls")
    public void export(HttpServletResponse response) {
        try (InputStream is = JxlsController.class.getClassLoader().getResourceAsStream("template/用户列表.xlsx");
             OutputStream os = response.getOutputStream()) {
            List<User> list = userService.selectList();
            String fileName = "用户列表.xlsx";
            fileName = new String(fileName.getBytes(), "ISO8859-1");
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            //这里的context是jxls框架上的context内容
            Context context = new Context();
            //将列表参数放入context中
            context.putVar("data", list);
            //将List<Exam>列表数据按照模板文件中的格式生成到scoreOutput.xls文件中
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
